/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package webserver;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author javi
 */
public class Servidor implements Runnable {

    //Declaracion de constantes//
    private static final String PREFIX_GET = "GET";
    private ServerSocket servidor;
    private Socket cliente;
    private DataInputStream entradaServidor;
    private PrintWriter salidaServidor;
    private byte[] buffer = new byte[1024];
    private BufferedReader br;
    private FileInputStream fis;
    private StringTokenizer tokens;

    public Servidor(int puerto) throws IOException {
        servidor = new ServerSocket(puerto);
    }

    public void aceptarConexion() {
        try {
            cliente = servidor.accept();
            System.out.println("Recibido cliente:" + cliente.getInetAddress().getHostAddress());
            entradaServidor = new DataInputStream(cliente.getInputStream());
            salidaServidor = new PrintWriter(cliente.getOutputStream(), true);
            br = new BufferedReader(new InputStreamReader(entradaServidor));
            tokens = new StringTokenizer(br.readLine());

            new Thread(new Runnable() {
                @Override
                public void run() {
                    procesarPeticion(tokens);
                }
            }).start();
        } catch (IOException ex) {
            Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void procesarPeticion(StringTokenizer peticion) {
        if (peticion.nextToken().equals(Servidor.PREFIX_GET)) {
            atenderPeticionGet(peticion);
        }

    }

    @Override
    public void run() {
        while (true) {
            aceptarConexion();
        }
    }

    private void atenderPeticionGet(StringTokenizer peticion) {
        System.out.println("Peticion recibida" + peticion);
        peticion.nextToken();
        String nombreFicheroSolicitado = peticion.nextToken();
        nombreFicheroSolicitado = "." + nombreFicheroSolicitado;
        try {
            fis = new FileInputStream(nombreFicheroSolicitado);
            salidaServidor.print(fis);
            cerrarConexion();
        } catch (FileNotFoundException ex) {
            devolverNoEncontrado();
        } catch (IOException ex) {
            Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void devolverNoEncontrado() {
        String notFound = "<html><body>"
                + "<h1>Error 404. File Not Found" + "</h1>"
                + "</body></html>";
        salidaServidor.print(notFound);
        salidaServidor.flush();
        try {
            cerrarConexion();
        } catch (IOException ex) {
            System.err.println("Error al cerrar la conexion");
        }
    }

    private void cerrarConexion() throws IOException {
        entradaServidor.close();
        salidaServidor.close();
        cliente.close();
    }
}
